<template>
  <div id="china-map" ref="projectMap" style="height: 100%">
  </div>
</template>

<script>
  // 中国地图
  require('echarts/map/js/world')

  import { mapGetters } from 'vuex'
  import latitude from './latitude'
  export default {
    name: 'chinaMap',
    data () {
      return {
        timer: null,
        onLineProjects: [],
        notOnLineProjects: [],
        allProjects: [],
        warnProjectsArray: {},
        chooseProjects: [],
        projectMap: null,
        picProjects: [],
        projectOption: {
          tooltip: {
            show: true,
            enterable: true,
            triggerOn: 'none',
            formatter: (params) => {
              return params.seriesName + ': ' + params.data.name
            },
            backgroundColor: 'rgba(0, 0, 0, 0.5)'
          },
          backgroundColor: '',
          // 标题
          title: {
            text: '',
            left: 'center',
            textStyle: {
              color: '#fff'
            }
          },
          // 图例按钮 点击可选择哪些不显示
          legend: {
            data: ['选中', '在线', '离线', '图集'],
            formatter: function (name) {
              return name
            },
            textStyle: {
              color: '#b3ddfb'
            }
          },
          // 地理坐标系组件
          geo: {
            map: 'world',
            left: '10%',
            right: '10%',
            roam: true,
            silent: true,
            scaleLimit: {
              min: 1,
              max: 20
            },
            label: {
              // true会显示城市名
              normal: {
                show: false,
                color: 'rgba(242,242,242,.3)'
              },
              emphasis: {
                show: false,
                color: 'rgba(242,242,242,.3)'
              }
            },
            itemStyle: {
              // 地图背景色
              normal: {
                areaColor: '#0f4264',
                borderColor: '#1c8da0'
              },
              // 悬浮时
              emphasis: {
                areaColor: ''
              }
            }
          },
          // 系列列表
          series: [
            {
              name: '选中',
              // 表的类型 这里是散点
              type: 'effectScatter',
              // 使用地理坐标系，通过 geoIndex 指定相应的地理坐标系组件
              coordinateSystem: 'geo',
              data: [],
              // 标记的大小
              symbolSize: 8,
              scale: 10,
              showEffectOn: 'render',
              rippleEffect: {
                brushType: 'stroke'
              },
              hoverAnimation: true,
              label: {
                normal: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  color: '#00ff12',
                  shadowBlur: 10,
                  shadowColor: '#333'
                }
              },
              z: 2
            },
            {
              name: '在线',
              // 表的类型 这里是散点
              type: 'scatter',
              // 使用地理坐标系，通过 geoIndex 指定相应的地理坐标系组件
              coordinateSystem: 'geo',
              data: [],
              // 标记的大小
              symbolSize: 5,
              z: 1,
              itemStyle: {
                normal: {
                  color: '#2cd7e8'
                },
                // 鼠标悬浮的时候圆点样式变化
                emphasis: {
                  borderColor: '#fff',
                  borderWidth: 1
                }
              }
            },
            {
              name: '离线',
              // 表的类型 这里是散点
              type: 'scatter',
              // 使用地理坐标系，通过 geoIndex 指定相应的地理坐标系组件
              coordinateSystem: 'geo',
              data: [],
              // 标记的大小
              symbolSize: 5,
              z: 1,
              // 鼠标悬浮的时候在圆点上显示数值
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  color: '#ead679'
                },
                // 鼠标悬浮的时候圆点样式变化
                emphasis: {
                  borderColor: '#fff',
                  borderWidth: 1
                }
              }
            },
            {
              name: '图集',
              // 表的类型 这里是散点
              type: 'scatter',
              // 使用地理坐标系，通过 geoIndex 指定相应的地理坐标系组件
              coordinateSystem: 'geo',
              data: [],
              // 标记的大小
              symbolSize: 5,
              z: 1,
              // 鼠标悬浮的时候在圆点上显示数值
              label: {
                normal: {
                  show: false
                },
                emphasis: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  color: '#FF8C00'
                },
                // 鼠标悬浮的时候圆点样式变化
                emphasis: {
                  borderColor: '#fff',
                  borderWidth: 1
                }
              }
            },
            {
              name: '警报',
              // 表的类型 这里是散点
              type: 'effectScatter',
              // 使用地理坐标系，通过 geoIndex 指定相应的地理坐标系组件
              coordinateSystem: 'geo',
              tooltip: {
                formatter: (params) => {
                  let res = `<a href="${this.$site.videoServer}/#/AIvideo?pjId=${this.warnProjectsArray.projectId}&name=${this.warnProjectsArray.projectName}">
                                <div style='background:#fff; position:relative'>
                                  <div style='position:absolute;bottom: -10px;left: 48%;width:0;height:0;border-left: 7px solid transparent;border-right: 7px solid transparent;border-top: 7px solid #fff;'></div>
                                  <img id ='loading' style='width:250px;height:150px;' src ='${params.data.value[3]}'/>
                                  <div style="color: #000; text-align:left">${params.data.name}</div>
                                  <div style="color: red; text-align:left">${params.data.value[4]}(${params.data.value[5]})</div>
                               </div>
                             </a>`
                  return res
                },
                backgroundColor: '#fff',
                position: function (point, params, dom, rect, size) {
                  // 其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
                  let x = point[0]
                  let y = point[1]
                  // var viewWidth = size.viewSize[0]
                  // var viewHeight = size.viewSize[1]
                  let boxWidth = size.contentSize[0]
                  let boxHeight = size.contentSize[1]
                  let posX = x - boxWidth / 2 - 3
                  //  坐标位置
                  let posY = y - boxHeight - 20
                  return [posX, posY]
                }
              },
              // 标记的大小
              symbolSize: 8,
              scale: 10,
              showEffectOn: 'render',
              rippleEffect: {
                brushType: 'stroke'
              },
              hoverAnimation: true,
              label: {
                normal: {
                  show: false
                }
              },
              itemStyle: {
                normal: {
                  color: '#ff0000',
                  shadowBlur: 10,
                  shadowColor: '#333'
                }
              },
              silent: true,
              z: 5
            }
          ]
        }
      }
    },
    props: {
      chooseProject: {
        type: Array,
        default: function () {
          return []
        }
      },
      warnProjects: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    watch: {
      chooseProject (data) {
        this.initChooseProjects(data)
      },
      warnProjects (data) {
        if (data.projectId) {
          this.initWarnProjects(data)
        } else {
          this.warnProjectsArray.location = null
          this.initWarnProjectsOption()
        }
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.init()
        this.getOrdinaryUserProjectList()
      })
    },
    computed: {
      ...mapGetters({
        currentUser: 'currentUser'
      })
    },
    beforeRouteLeave (to, from, next) {
      window.clearInterval(this.timer)
      next()
    },
    methods: {
      getOrdinaryUserProjectList () {
        // let departmentId = this.currentUser.departmentId
        // if (this.currentUser.advancedAdmin) {
        //   departmentId = ''
        // }
        const data = {
          'coId': this.currentUser.coId,
          // 'departmentId': departmentId,
          'mid': this.currentUser.mid
        }
        this.$axios({
          method: 'post',
          url: `${this.$site.videoServer}/api/hikvision8700/getOrdinaryUserProjectList`,
          data: this.$qs.stringify(data)
        }).then(res => {
          this.initOnLineProjects(res.data.data.onLineProjects)
          this.initPicProjects(res.data.data.picProjects)
          this.initNotOnLineProjects(res.data.data.allProjects, res.data.data.onLineProjects)
          let onLineProjectsLength = res.data.data.onLineProjects.length
          let allProjectsLength = res.data.data.allProjects.length
          this.allProjects = res.data.data.allProjects
          if (onLineProjectsLength > 0 && allProjectsLength > 0) {
            let onOffProjectsLength = allProjectsLength - onLineProjectsLength
            let projectRate = ((onLineProjectsLength) / allProjectsLength).toFixed(2) * 100
            this.$store.commit('setVideoNodeCompany', {company: (onLineProjectsLength), companyOffline: onOffProjectsLength, companyRate: projectRate})
          }
        })
      },
      async initPicProjects (items) {
        const loadData = item => new Promise(resolve => {
          if (item.pointx && item.pointy) {
            item.location = {name: item.projectTitle, value: [item.pointx, item.pointy, item.projectId]}
            resolve(item)
          } else {
            this.$jsonp(`https://api.map.baidu.com/geocoder/v2/?address=${item.address}&output=json&ak=MErGAwKAYaNnw8jTxTX0hYyscdcdH8Rl`,
            ).then(json => {
              const {lat, lng} = json.result.location
              item.location = {name: item.projectTitle, value: [lng, lat, item.projectId]}
              resolve(item)
            })
          }
        })
        for (let i = 0; i < items.length; i++) {
          const data = await loadData(items[i])
          this.picProjects.push(data)
        }
        this.initPicProjectsOption()
      },
      async initOnLineProjects (items) {
        const loadData = item => new Promise(resolve => {
          if (item.pointx && item.pointy) {
            item.location = {name: item.projectTitle, value: [item.pointx, item.pointy, item.projectId]}
            resolve(item)
          } else {
            this.$jsonp(`https://api.map.baidu.com/geocoder/v2/?address=${item.address}&output=json&ak=MErGAwKAYaNnw8jTxTX0hYyscdcdH8Rl`,
            ).then(json => {
              const {lat, lng} = json.result.location
              item.location = {name: item.projectTitle, value: [lng, lat, item.projectId]}
              resolve(item)
            })
          }
        })
        for (let i = 0; i < items.length; i++) {
          const data = await loadData(items[i])
          this.onLineProjects.push(data)
        }
        this.initOnLineProjectsOption()
      },
      async initNotOnLineProjects (allProjects, onLineProjects) {
        const loadData = item => new Promise(resolve => {
          if (item.pointx && item.pointy) {
            item.location = {name: item.projectTitle, value: [item.pointx, item.pointy, item.projectId]}
            resolve(item)
          } else {
            this.$jsonp(`https://api.map.baidu.com/geocoder/v2/?address=${item.address}&output=json&ak=MErGAwKAYaNnw8jTxTX0hYyscdcdH8Rl`,
            ).then(json => {
              const {lat, lng} = json.result.location
              item.location = {name: item.projectTitle, value: [lng, lat, item.projectId]}
              resolve(item)
            })
          }
        })
        let onLineProjectId = onLineProjects.map((item) => {
          return item.projectId
        })
        let offlineProject = allProjects.filter((item) => !onLineProjectId.includes(item.projectId))
        this.$emit('Offline', offlineProject)
        for (let i = 0; i < offlineProject.length; i++) {
          const data = await loadData(offlineProject[i])
          this.notOnLineProjects.push(data)
        }
        this.initNotOnLineProjectsOption()
      },
      async initChooseProjects (items) {
        if (items.length > 0) {
          const loadData = item => new Promise(resolve => {
            if (item.pointx && item.pointy) {
              item.location = {name: item.projectTitle, value: [item.pointx, item.pointy, item.projectId]}
              resolve(item)
            } else if (item.address) {
              this.$jsonp(`https://api.map.baidu.com/geocoder/v2/?address=${item.address}&output=json&ak=MErGAwKAYaNnw8jTxTX0hYyscdcdH8Rl`,
              ).then(json => {
                if (json.result) {
                  const {lat, lng} = json.result.location
                  item.location = {name: item.projectTitle, value: [lng, lat, item.projectId]}
                  resolve(item)
                }
              })
            } else {
              resolve(item)
            }
          })
          this.chooseProjects = []
          for (let i = 0; i < items.length; i++) {
            const data = await loadData(items[i])
            this.chooseProjects.push(data)
          }
        } else {
          this.chooseProjects = []
        }
        this.initChooseProjectsOption()
      },
      async initWarnProjects (item) {
        const loadImg = item => new Promise(resolve => {
          this.$store.dispatch({
            type: 'downFile',
            fileUuid: item.picUrl,
            td: 2
          }).then(res => {
            item.imgurl = res
            resolve()
          })
        })
        const loadData = item => new Promise(resolve => {
          let project = this.allProjects.find(project => project.projectId === item.projectId)
          item.formatTime = this.$moment(item.time).format('YYYY-MM-DD, HH:mm:ss')
          if (project.pointx && project.pointy) {
            item.location = {name: item.projectName, value: [project.pointx, project.pointy, item.projectId, item.imgurl, item.typeName, item.formatTime]}
            resolve(item)
          } else {
            this.$jsonp(`https://api.map.baidu.com/geocoder/v2/?address=${project.address}&output=json&ak=MErGAwKAYaNnw8jTxTX0hYyscdcdH8Rl`,
            ).then(json => {
              if (json.result) {
                const {lat, lng} = json.result.location
                item.location = {name: item.projectName, value: [lng, lat, item.projectId, item.imgurl, item.typeName, item.formatTime]}
                resolve(item)
              }
            })
          }
        })
        await loadImg(item)
        await loadData(item)
        this.warnProjectsArray = item
        this.initWarnProjectsOption()
      },
      init () {
        this.projectMap = this.$echarts.init(this.$refs.projectMap)
        this.projectMap.setOption(this.projectOption)
        this.projectMap.on('click', (parmas) => {
          this.projectMapClick(parmas)
        })
        this.projectMap.on('dblclick', (parmas) => {
          this.projectMapDblclick(parmas)
        })
        this.projectMap.on('mouseover', (parmas) => {
          let seriesIndex = parmas.seriesIndex
          let dataIndex = parmas.dataIndex
          if (this.warnProjectsArray.projectId === parmas.value[2]) {
            seriesIndex = 3
            dataIndex = 0
          }
          this.projectMap.dispatchAction({
            type: 'showTip',
            seriesIndex: seriesIndex,
            dataIndex: dataIndex
          })
        })
        this.projectMap.on('mouseout', (parmas) => {
          if (this.warnProjectsArray.projectId) {
            if (this.warnProjectsArray.projectId !== parmas.value[2]) {
              this.projectMap.dispatchAction({
                type: 'showTip',
                seriesIndex: 3,
                dataIndex: 0
              })
            }
          } else {
            this.projectMap.dispatchAction({
              type: 'hideTip',
              seriesIndex: parmas.seriesIndex,
              dataIndex: parmas.dataIndex
            })
          }
        })
      },
      projectMapClick (item) {
        if (item.componentType === 'geo') {
          this.projectMap.setOption({
            geo: {
              center: [latitude[item.name][1], latitude[item.name][0]],
              zoom: 6,
              animationDurationUpdate: 1000,
              animationEasingUpdate: 'cubicInOut'
            }
          })
        } else {
          let AiLength = this.allProjects.filter(project => {
            if (project.projectId === item.value[2] && project.aiId) {
              return project
            }
          })
          if (AiLength.length > 0) {
            this.$router.push({name: 'AIvideo', query: {pjId: item.value[2], name: item.name}})
          } else {
            if (item.seriesName === '图集') {
              this.$router.push({name: 'picture', query: {pjId: item.value[2], name: item.name}})
            } else {
              this.$router.push({name: 'videoProject', query: {pjId: item.value[2], name: item.name}})
            }
          }
        }
      },
      projectMapDblclick () {
        this.projectMap.setOption({
          geo: {
            zoom: 1,
            center: [104.5, 34.5],
            animationDurationUpdate: 1000,
            animationEasingUpdate: 'cubicInOut'
          }
        })
      },
      initOnLineProjectsOption () {
        const location = this.onLineProjects.map((item) => {
          return item.location
        })
        this.projectMap.setOption({
          series: [
            {
              name: '在线',
              data: location
            }
          ]
        })
      },
      initNotOnLineProjectsOption () {
        const location = this.notOnLineProjects.map((item) => {
          return item.location
        })
        this.projectMap.setOption({
          series: [
            {
              name: '离线',
              data: location
            }
          ]
        })
      },
      initChooseProjectsOption () {
        const location = this.chooseProjects.map((item) => {
          return item.location
        })
        this.projectMap.setOption({
          series: [
            {
              name: '选中',
              data: location
            }
          ]
        })
      },
      initPicProjectsOption () {
        const location = this.picProjects.map((item) => {
          return item.location
        })
        this.projectMap.setOption({
          series: [
            {
              name: '图集',
              data: location
            }
          ]
        })
      },
      initWarnProjectsOption () {
        this.projectMap.setOption({
          series: [
            {
              name: '警报',
              data: [this.warnProjectsArray.location]
            }
          ]
        })
        this.projectMap.dispatchAction({
          type: 'showTip',
          seriesIndex: 3,
          dataIndex: 0
        })
      }
    }
  }
</script>
